import { NextApiRequest, NextApiResponse } from 'next';
import jwt from 'jsonwebtoken';

const SECRET_KEY = process.env.JWT_SECRET || 'your-secret-key';

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  console.log('API route hit');
  console.log('Request headers:', req.headers);

  if (req.method !== 'GET') {
    return res.status(405).end(); // Method Not Allowed
  }

  const authHeader = req.headers.authorization;
  console.log('Auth header:', authHeader);

  if (!authHeader) {
    return res.status(401).json({ message: 'Authorization header missing' });
  }

  const token = authHeader.split(' ')[1];
  console.log('Extracted token:', token);

  if (!token) {
    return res.status(401).json({ message: 'Token missing' });
  }

  try {
    console.log('Attempting to verify token with secret:', SECRET_KEY);
    const decoded = jwt.verify(token, SECRET_KEY) as { email: string };
    console.log('Decoded token:', decoded);
    res.status(200).json({ email: decoded.email });
  } catch (error) {
    console.error('Token verification error:', error);
    res.status(401).json({ message: 'Invalid token' });
  }
}